package com.neo.tiny.middle.file.storage.impl;

import cn.hutool.core.util.StrUtil;
import com.neo.tiny.admin.sysConfig.bean.StorageClientConfig;
import com.neo.tiny.middle.file.enums.StorageType;
import com.neo.tiny.middle.file.storage.AbstractStorageClient;
import io.minio.MinioClient;
import io.minio.ObjectWriteArgs;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @Description: minio存储实现
 * @Author: yqz
 * @CreateDate: 2022/11/14 23:10
 */
@Slf4j
@Component
public class MinioStorageImpl extends AbstractStorageClient {

    // TODO 待优化，优化为修改存储配置自动更新MinioClient客户端，而不是每次初始化
    public MinioClient getMinioClient() {

        StorageClientConfig config = getClientConfig();
        StorageClientConfig.MinIO minIo = config.getMinIo();
        String endpoint = minIo.getEndpoint();
        String accessKey = minIo.getAccessKey();
        String secretKey = minIo.getSecretKey();

        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
    @Override
    @SneakyThrows
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {

        MinioClient client = getMinioClient();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(getClientConfig().getMinIo().getBucketName())
                .object(keyName)
                .contentType(contentType)
                .stream(inputStream, contentLength, ObjectWriteArgs.MIN_MULTIPART_SIZE)
                .build();

        ObjectWriteResponse response = client.putObject(putObjectArgs);
        log.info("这里是 minio storage,上传结果：{}", response);
    }

    @Override
    public String generateUrl(String keyName) {
        StorageClientConfig config = getClientConfig();
        StorageClientConfig.MinIO minIo = config.getMinIo();

        return StrUtil.C_SLASH + minIo.getBucketName() + StrUtil.C_SLASH + keyName;
    }


    @Override
    public Boolean support(String storageType) {
        return StorageType.MINIO.getStorageType().equals(storageType);
    }
}
